<template>
	<view>
		<view class="content" v-if="dataList.length < 1">
			<u-empty text="有朋致远方来,不亦悦乎" mode="list"></u-empty>
		</view>
		<view v-else>
			<u-swipe-action :show="item.show" :index="index" v-for="(item, index) in dataList" :key="item.id"
				@click="click" @open="open" :options="options">
				<view class="item u-border-bottom" @click.stop="pageToGroupDetail(item)">
					<view style="display: flex;width: 100%;">
						<image mode="aspectFill" :src="item.sysFileInfo.fileUrl" />
						<!-- 此层wrap在此为必写的，否则可能会出现标题定位错误 -->
						<view class="title-wrap" style="flex:2">
							<text class="title u-line-2">{{ item.groupName }}</text>
						</view>
						<view class="title-wrap" style="flex:1">
							<view class="title u-line-2 right-label">
								<u-icon name="arrow-left-double"></u-icon>
								<text> 向左滑动</text>
							</view>
						</view>
					</view>
				</view>
			</u-swipe-action>
			<u-loadmore status="nomore" />
		</view>
		<view class="fix-button-space">
			<view>
				<button plain="true" @click="addGroupPop">
					<view class="fix-button-space-view">
						<view><u-icon name="plus-people-fill" color="#29C153" size="45"></u-icon></view>
						<text>新建</text>
					</view>
				</button>
			</view>
			<view>
				<button plain="true" @click="applyPopShow = true">
					<view class="fix-button-space-view">
						<view><u-icon name="list-dot" color="#29C153" size="45"></u-icon></view>
						<text>记录</text>
					</view>
				</button>
			</view>
			<view>
				<button plain="true" @click="pageToGroupSearch">
					<view class="fix-button-space-view">
						<view><u-icon name="search" color="#29C153" size="45"></u-icon></view>
						<text>搜索</text>
					</view>
				</button>
			</view>
		</view>
		<u-popup v-model="addGroupPopShow" mode="top" border-radius="30" width="60%">
			<view style="padding: 0 10%;">
				<u-form :model="formData" ref="uForm">
					<u-form-item label="圈子头像:" label-width="150">
						<u-upload ref="uUpload" :action="action" :auto-upload="true" :header="header" max-count="1"
							width="120" height="120" v-if="!isEdit"></u-upload>
						<view @click="resetImage()">
							<u-image width="120rpx" height="120rpx" :src="formData.image" v-if="isEdit"></u-image>
						</view>
					</u-form-item>
					<u-form-item label="圈子名称:" label-width="150" prop="groupName">
						<u-input v-model="formData.groupName" type="text" :border="false" confirm-type="done"
							placeholder="输入圈子名称" @confirm="submit()" />
					</u-form-item>
				</u-form>
			</view>
		</u-popup>
		<u-popup v-model="applyPopShow" mode="bottom" border-radius="30" height="400px">
			<u-subsection :list="navList" :current="currentNav" @change="changeContentType"></u-subsection>
			<uni-list v-if="currentNav === 0">
				<uni-list :border="true">
					<!-- 右侧带角标 -->
					<uni-list-chat :title="item.group.groupName" :avatar="item.sysFileInfo.fileUrl"
						:note="formatTime(item.updateTime,'{y}-{m}-{d}')" :style="{ color:item.review === 0 ? '#ff9900':'#19be6b'  }"
						v-for="(item, index) in ownGroupInviteList" :key="index">
						<text>
							{{item.review === 0 ? '待审核' : (item.review === 1 ? '同意':'拒绝')}}
						</text>
					</uni-list-chat>

				</uni-list>
			</uni-list>
			<uni-list v-if="currentNav === 1">
				<uni-list :border="true">
					<!-- 右侧带角标 -->
					<uni-list-chat :avatar-circle="true" :title="item.user.nickName" clickable
						@click="updateStatus(item)" :avatar="baseUrl + item.user.avatar"
						:note="text+item.group.groupName" :style="{ color:item.review === 0 ? '#ff9900':'#19be6b'  }"
						v-for="(item, index) in otherGroupInviteList" :key="index">
						<text>
							{{item.review === 0 ? '待审核' : (item.review === 1 ? '同意':'拒绝')}}
						</text>
					</uni-list-chat>
				</uni-list>
			</uni-list>
		</u-popup>
		<u-action-sheet :list="actionList" v-model="actionShow" :cancel-btn="true"
			@click="settingOfOption"></u-action-sheet>
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	import {
		getGroupList,
		addGroup,
		updateGroup,
		removeGroup,
	} from '@/api/bot/group'
	import {
		getGroupInviteList,
		updateGroupInvite
	} from '@/api/bot/groupInvite'
	import config from '@/config'
	import {
		getToken
	} from '@/utils/auth'
	export default {
		data() {
			return {
				baseUrl: config.baseUrl,
				query: {
					pageNum: 1,
					pageSize: 10,
					isPage: true
				},
				dataList: [],
				disabled: false,
				btnWidth: 180,
				show: false,
				options: [{
						text: '编辑',
						style: {
							backgroundColor: '#007aff'
						}
					},
					{
						text: '删除',
						style: {
							backgroundColor: '#dd524d'
						}
					}
				],
				addGroupPopShow: false,
				formData: {
					image: '',
					groupName: ''
				},
				rules: {
					groupName: [{
						required: true,
						message: '请输入圈子名称',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change', 'blur'],
					}],
					image: [{
						required: true,
						message: '请上传圈子头像',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change', 'blur'],
					}],
				},
				action: config.baseUrl + '/common/upload',
				header: '',
				isEdit: false,
				avatarList: [{
					url: 'https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/unicloudlogo.png'
				}, {
					url: 'https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/unicloudlogo.png'
				}, {
					url: 'https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/unicloudlogo.png'
				}],
				applyPopShow: false,
				groupInviteList: [],
				ownGroupInviteList: [],
				otherGroupInviteList: [],
				groupInviteQuery: {
					pageNum: 1,
					pageSize: 10,
					ownApply: false
				},
				navList: [{
					name: '我的申请'
				}, {
					name: '申请审核'
				}],
				currentNav: 0,
				text: '申请加入',
				actionList: [{
					text: '同意',
					color: '#19be6b',
				}, {
					text: '拒绝',
					color: '#fa3534',
				}],
				actionShow: false,
				currentUser: ''
			}
		},
		onLoad() {
			this.header = this.header || {}
			if (getToken()) {
				this.header['Authorization'] = 'Bearer ' + getToken()
			}
			this.getGroupList()
			this.getOwnGroupInviteList()
			this.getOtherGroupInviteList()
		},
		onPullDownRefresh() {
			this.getGroupList()
			this.getOwnGroupInviteList()
			this.getOtherGroupInviteList()
			setTimeout(() => {
				uni.stopPullDownRefresh()
			}, 1500)
		},
		methods: {
			getGroupList() {
				uni.showLoading({
					title: "加载中..."
				})
				getGroupList(this.query).then(res => {
					this.dataList = res.rows
					uni.hideLoading();
				})
			},
			getOwnGroupInviteList() {
				let query = {
					...this.groupInviteQuery,
					ownApply: true
				}
				getGroupInviteList(query).then(res => {
					res.rows.forEach(element => {
						element.updateTime = new Date(element.updateTime).getTime()
					})
					this.ownGroupInviteList = res.rows
				})
			},
			getOtherGroupInviteList() {
				let query = {
					...this.groupInviteQuery,
					ownApply: false
				}
				getGroupInviteList(query).then(res => {
					this.otherGroupInviteList = res.rows
				})
			},
			click(index, index1) {
				if (index1 == 1) {
					this.$modal.confirm('确定删除该圈子吗？').then(() => {
						this.dataList[index].show = false;
						removeGroup(this.dataList[index]).then(res => {
							if (res.code == 200) {
								this.$modal.msgSuccess("删除成功");
								this.dataList.splice(index, 1);
							} else {
								this.$modal.msgError("删除失败");
							}
						})
					})
				} else {
					this.dataList[index].show = false;
					let data = this.dataList[index]
					this.isEdit = true
					this.formData = data
					this.formData.image = data.sysFileInfo.fileUrl
					this.addGroupPopShow = true
				}
			},
			// 如果打开一个的时候，不需要关闭其他，则无需实现本方法
			open(index) {
				// 先将正在被操作的swipeAction标记为打开状态，否则由于props的特性限制，
				// 原本为'false'，再次设置为'false'会无效
				this.dataList[index].show = true;
				this.dataList.map((val, idx) => {
					if (index != idx) this.dataList[idx].show = false;
				})
			},
			pageToGroupDetail(obj) {
				obj.router = 'own'
				const formDataStr = JSON.stringify(obj);
				this.$tab.navigateTo('/pages/detail/groupDetail?data=' + encodeURIComponent(formDataStr))
			},
			pageToGroupSearch() {
				this.$tab.navigateTo('/pages/mine/bot/ownGroup/searchGroup')
			},
			openNoticeList() {

			},
			getImageInfo() {
				return new Promise((resolve, reject) => {
					let files = [];
					files = this.$refs.uUpload.lists.filter(val => {
						return val.progress == 100;
					})
					files.forEach(element => {
						const result = element.response;
						let temp = {
							fileName: result.newFileName,
							fileLocation: result.fileName,
							fileUrl: result.url
						}
						this.formData.image = temp.fileUrl;
						this.formData.sysFileInfo = temp;
					})
					if (this.formData.image) {
						return resolve(true);
					} else {
						return resolve(false);
					}
				})
			},
			async submit() {
				let result = await this.getImageInfo();
				if (result) {
					this.$refs.uForm.validate(valid => {
						if (valid) {
							if (!this.formData.id) {
								addGroup(this.formData).then(res => {
									if (res.code == 200) {
										this.$modal.msgSuccess("创建成功")
										this.getGroupList()
										this.addGroupPopShow = false
									} else {
										this.$modal.msgError("创建失败")
									}
								})
							} else {
								updateGroup(this.formData).then(res => {
									if (res.code == 200) {
										this.$modal.msgSuccess("更新成功")
										this.getGroupList()
										this.addGroupPopShow = false
									} else {
										this.$modal.msgError("更新失败")
									}
								})
							}
						} else {
							console.log('验证失败');
						}
					});
				} else {
					this.$refs.uToast.show({
						title: `获取文件信息失败`,
						type: 'error',
					})
				}
			},
			addGroupPop() {
				this.isEdit = false
				this.addGroupPopShow = true
			},
			resetImage() {
				this.$modal.confirm('是否要重新上传吗？').then(() => {
					this.isEdit = false;
				});
			},
			changeContentType(index) {
				this.currentNav = index
			},
			updateGroupInvite() {
				updateGroupInvite(this.currentUser).then(res => {
					if (res.code == 200) {
						this.$modal.msgSuccess("审核成功")
						this.getOtherGroupInviteList()
					} else {
						this.$modal.msgError("审核失败")
					}
				})
			},
			updateStatus(obj) {
				this.currentUser = obj
				if (obj.review === 0) {
					this.actionShow = true
				} else {
					this.$refs.uToast.show({
						title: `该申请已审核完毕`,
						type: 'warning',
					})
				}
			},
			settingOfOption(index) {
				if (index === 0) {
					this.currentUser.review = 1
				} else {
					this.currentUser.review = 2
				}
				this.updateGroupInvite()
			}
		},
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		flex: 1;
		display: flex;
		justify-content: center;
		align-items: center;
		margin-top: 10%;
	}

	.item {
		display: flex;
		padding: 20rpx;
	}

	.right-label {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	image {
		width: 150rpx;
		flex: 0 0 150rpx;
		height: 150rpx;
		margin-right: 20rpx;
		border-radius: 12rpx;
	}

	.title {
		text-align: left;
		font-size: 28rpx;
		color: $u-content-color;
	}

	.fix-button-space {
		border-radius: 30rpx;
		box-shadow: 5px 10px 10px 5px #0000001A;
		background-color: white;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 1% 0%;
		color: #999999;
		font-size: 14rpx;
		height: 110rpx;
		position: fixed;
		width: 65%;
		bottom: 20px;
		left: 17.5%;
		right: 17.5%;
	}

	// .fix-button-space view:nth-child(1) {
	// 	height: 100%;
	// 	flex: 1
	// }

	.fix-button-space button {
		background-color: transparent;
		color: #999999;
		font-size: 14px;
	}

	.fix-button-space-view {
		display: flex;
		align-items: center;
		flex-direction: column;
	}

	.fix-button-space-view text {
		margin-top: -25rpx;
		width: 120rpx;
	}


	button[plain] {
		border: 0
	}

	button::after {
		border: none;
	}
</style>